package com.lyf.boot.spring.aop;

import cn.hutool.core.lang.Dict;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.lyf.boot.annotation.Log;
import com.lyf.boot.base.system.dao.BaseSysOperLogDao;
import com.lyf.boot.base.system.entity.SysOperLog;
import com.lyf.boot.enums.BusinessStatus;
import com.lyf.boot.utils.AuthUtil;
import com.lyf.boot.utils.JsonUtil;
import com.lyf.boot.utils.ServerUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerMapping;

import java.util.Collection;
import java.util.Map;

/**
 * 日志切面
 * @author Luyufan
 * @date 2023/7/7 18:23
 */
@Slf4j
@Aspect
@Component
@RequiredArgsConstructor
public class LogAspect {

    /**
     * 排除敏感属性字段
     */
    public static final String[] EXCLUDE_PROPERTIES = { "password", "oldPassword", "newPassword", "confirmPassword" };

    private final BaseSysOperLogDao sysOperLogDao;

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "@annotation(controllerLog)", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Log controllerLog, Object jsonResult) {
        handleLog(joinPoint,controllerLog, null, jsonResult);
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e         异常
     */
    @AfterThrowing(value = "@annotation(controllerLog)", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Log controllerLog, Exception e) {
        handleLog(joinPoint,controllerLog,e, null);
    }

    protected void handleLog(final JoinPoint joinPoint, Log controllerLog, final Exception e, Object jsonResult) {
        try {
            // *========数据库日志=========*//
            SysOperLog sysOperLog = new SysOperLog();
            HttpServletRequest request = ServerUtil.request();
            String ip = ServerUtil.clientIp();
            sysOperLog.setOperIp(ip);
            String operLocation = ServerUtil.getIpRegion(ip);
            sysOperLog.setOperLocation(operLocation);
            sysOperLog.setOperUrl(request.getRequestURI());
            sysOperLog.setUserId(AuthUtil.getUserId());
            sysOperLog.setStatus(BusinessStatus.SUCCESS.ordinal());
            if(null != e){
                sysOperLog.setStatus(BusinessStatus.FAIL.ordinal());
                sysOperLog.setErrorMsg(StrUtil.subPre(e.getMessage(), 2000));
            }
            // 设置方法名称
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            sysOperLog.setMethod(className + "." + methodName + "()");
            // 设置请求方式
            sysOperLog.setRequestMethod(request.getMethod());
            getControllerMethodDescription(joinPoint, controllerLog, sysOperLog, jsonResult);
            sysOperLogDao.insert(sysOperLog);
        } catch (Exception ex) {
            // 记录本地异常日志
            log.error("==前置通知异常==");
            log.error("异常信息", ex);
        }
    }

    public void getControllerMethodDescription(JoinPoint joinPoint, Log controllerLog, SysOperLog sysOperLog, Object jsonResult) throws Exception {
        sysOperLog.setModule(controllerLog.module());
        sysOperLog.setBusiness(controllerLog.business());
        sysOperLog.setBusinessType(controllerLog.businessType().ordinal());
        if(controllerLog.isSaveRequestData()){
            //
            setRequestValue(joinPoint, sysOperLog);
        }
        if(controllerLog.isSaveResponseData() && ObjectUtil.isNotEmpty(jsonResult)){
            //
            sysOperLog.setJsonResult(StrUtil.subPre(JsonUtil.toJsonString(jsonResult), 2000));
        }
    }

    private void setRequestValue(JoinPoint joinPoint, SysOperLog sysOperLog) throws Exception {
        String requestMethod = sysOperLog.getRequestMethod();
        if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod)) {
            String params = argsArrayToString(joinPoint.getArgs());
            sysOperLog.setOperParam(StrUtil.subPre(params, 2000));
        } else {
            Map<?, ?> paramsMap = (Map<?, ?>) ServerUtil.request().getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
            sysOperLog.setOperParam(StrUtil.subPre(paramsMap.toString(),  2000));
        }
    }

    /**
     * 参数拼装
     */
    private String argsArrayToString(Object[] paramsArray) {
        StringBuilder params = new StringBuilder();
        if (paramsArray != null) {
            for (Object o : paramsArray) {
                if (ObjectUtil.isNotNull(o) && !isFilterObject(o)) {
                    try {
                        String str = JsonUtil.toJsonString(o);
                        Dict dict = JsonUtil.parseMap(str);
                        if(MapUtil.isNotEmpty(dict)){
                            MapUtil.removeAny(dict, EXCLUDE_PROPERTIES);
                            str = JsonUtil.toJsonString(dict);
                        }
                        params.append(str).append(" ");
                    } catch (Exception e) {
                        log.error("==参数拼装异常==", e);
                    }
                }
            }
        }
        return params.toString().trim();
    }

    /**
     * 判断是否需要过滤的对象。
     *
     * @param o 对象信息。
     * @return 如果是需要过滤的对象，则返回true；否则返回false。
     */
    @SuppressWarnings("rawtypes")
    public boolean isFilterObject(final Object o) {
        Class<?> clazz = o.getClass();
        if (clazz.isArray()) {
            return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
        } else if (Collection.class.isAssignableFrom(clazz)) {
            Collection collection = (Collection) o;
            for (Object value : collection) {
                return value instanceof MultipartFile;
            }
        } else if (Map.class.isAssignableFrom(clazz)) {
            Map map = (Map) o;
            for (Object value : map.entrySet()) {
                Map.Entry entry = (Map.Entry) value;
                return entry.getValue() instanceof MultipartFile;
            }
        }
        return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse
                || o instanceof BindingResult;
    }


}
